package com.nulldev.util.security.encryptAPI.impls.xxtea;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class XXTEA extends Encryptor {

	public XXTEA(final String key) {
		this(Base64.decodeBase64(key));
	}

	public XXTEA(final byte[] key) {
		super("encryptapi.legacy.xxtea", new String[]
			{ "XXTEA" }, key);
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return XXTEACipher.encrypt((byte[]) o, this.key);
		} else if (o instanceof String) {
			return XXTEACipher.encrypt((String) o, this.key);
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return XXTEACipher.encryptToBase64String((byte[]) o, this.key);
		} else if (o instanceof String) {
			return XXTEACipher.encryptToBase64String((String) o, this.key);
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String o) {
		Variables.notNullE(o);
		if (o.isEmpty())
			throw new IllegalArgumentException("o is empty!");
		return XXTEACipher.decryptBase64StringToString((String) o, this.key);
	}

	@Override
	public byte[] decryptToBytes(byte[] o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return XXTEACipher.decrypt(o, this.key);
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return Base64.encodeBase64String(this.key);
	}
}
